document.addEventListener('DOMContentLoaded', function() {
    // 初始化用户信息
    initUserInfo();
    
    // 初始化任务列表
    initTaskList();
    
    // 初始化签到功能
    initSignIn();
    
    // 初始化任务进度监听
    initTaskProgress();
});

// 初始化用户信息
function initUserInfo() {
    const coinInfo = document.querySelector('.zheng_coin_info strong');
    coinInfo.textContent = taskData.userInfo.coins;
}

// 初始化任务列表
function initTaskList() {
    const taskList = document.querySelector('.zheng_task_list');
    const dailyTasks = taskData.tasks.daily;
    
    taskList.innerHTML = '';
    dailyTasks.forEach(task => {
        const taskElement = createTaskElement(task);
        taskList.appendChild(taskElement);
    });
}

// 创建任务元素
function createTaskElement(task) {
    const div = document.createElement('div');
    div.className = 'zheng_task_item';
    div.innerHTML = `
        <div class="zheng_task_content">
            <i class="iconfont icon-${task.type}"></i>
            <div class="zheng_task_info">
                <h3>${task.title}</h3>
                <p>${task.desc}</p>
                <div class="zheng_progress">
                    <div class="zheng_progress_bar" style="width: ${(task.currentProgress / task.maxProgress) * 100}%"></div>
                    <span>${task.currentProgress}/${task.maxProgress}</span>
                </div>
            </div>
        </div>
        <button class="zheng_task_btn" onclick="goToTask(${task.id})">${task.currentProgress >= task.maxProgress ? '已完成' : '去完成'}</button>
    `;
    
    return div;
}

// 签到功能
function initSignIn() {
    const signBtn = document.querySelector('.zheng_sign_btn');
    
    // 检查今日是否已签到
    checkSignInStatus();
    
    signBtn.addEventListener('click', function() {
        if (!isSignedToday()) {
            signIn();
        }
    });
}

// 检查签到状态
function checkSignInStatus() {
    const signBtn = document.querySelector('.zheng_sign_btn');
    if (isSignedToday()) {
        signBtn.textContent = '今日已签到';
        signBtn.disabled = true;
    }
}

// 判断今日是否已签到
function isSignedToday() {
    const lastSignIn = taskData.userInfo.lastSignIn;
    if (!lastSignIn) return false;
    
    const today = new Date().toDateString();
    return new Date(lastSignIn).toDateString() === today;
}

// 执行签到
function signIn() {
    taskData.userInfo.lastSignIn = new Date().toISOString();
    taskData.userInfo.signInDays++;
    taskData.userInfo.coins += 20;
    
    // 更新UI
    updateUserInfo();
    showToast('签到成功，获得20金币');
}

// 任务进度监听
function initTaskProgress() {
    // 监听阅读文章
    document.addEventListener('articleRead', () => {
        updateTaskProgress(1);
    });
    
    // 监听视频观看
    document.addEventListener('videoWatched', () => {
        updateTaskProgress(2);
    });
    
    // 监听文章分享
    document.addEventListener('articleShared', () => {
        updateTaskProgress(3);
    });
}

// 更新任务进度
function updateTaskProgress(taskId) {
    const task = taskData.tasks.daily.find(t => t.id === taskId);
    if (task && task.currentProgress < task.maxProgress) {
        task.currentProgress++;
        
        // 更新UI
        updateTaskUI(task);
        
        // 完成任务奖励
        if (task.currentProgress === task.maxProgress) {
            completeTask(task);
        }
    }
}

// 更新任务UI
function updateTaskUI(task) {
    const taskElement = document.querySelector(`.zheng_task_item[data-task-id="${task.id}"]`);
    if (taskElement) {
        const progressBar = taskElement.querySelector('.zheng_progress_bar');
        const progressText = taskElement.querySelector('.zheng_progress span');
        const taskBtn = taskElement.querySelector('.zheng_task_btn');
        
        progressBar.style.width = `${(task.currentProgress / task.maxProgress) * 100}%`;
        progressText.textContent = `${task.currentProgress}/${task.maxProgress}`;
        
        if (task.currentProgress >= task.maxProgress) {
            taskBtn.textContent = '已完成';
            taskBtn.disabled = true;
        }
    }
}

// 完成任务奖励
function completeTask(task) {
    taskData.userInfo.coins += task.reward;
    updateUserInfo();
    showToast(`任务完成，获得${task.reward}金币`);
}

// 更新用户信息
function updateUserInfo() {
    const coinInfo = document.querySelector('.zheng_coin_info strong');
    coinInfo.textContent = taskData.userInfo.coins;
}

// 显示提示信息
function showToast(message) {
    const toast = document.createElement('div');
    toast.className = 'zheng_toast';
    toast.textContent = message;
    
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.classList.add('show');
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => {
                document.body.removeChild(toast);
            }, 200);
        }, 2000);
    }, 10);
}

// 跳转到对应任务
function goToTask(taskId) {
    const task = taskData.tasks.daily.find(t => t.id === taskId);
    if (task) {
        switch (task.type) {
            case 'read':
                window.location.href = 'shouye.html';
                break;
            case 'video':
                window.location.href = 'video.html';
                break;
            case 'share':
                showShareDialog();
                break;
        }
    }
}

// 显示分享对话框
function showShareDialog() {
    const modal = document.createElement('div');
    modal.className = 'zheng_share_modal';
    modal.innerHTML = `
        <div class="zheng_share_content">
            <h3>分享到</h3>
            <div class="zheng_share_options">
                <div class="zheng_share_item">
                    <i class="iconfont icon-wechat"></i>
                    <span>微信</span>
                </div>
                <div class="zheng_share_item">
                    <i class="iconfont icon-weibo"></i>
                    <span>微博</span>
                </div>
                <div class="zheng_share_item">
                    <i class="iconfont icon-qq"></i>
                    <span>QQ</span>
                </div>
            </div>
            <button class="zheng_close_btn">取消</button>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    modal.querySelector('.zheng_close_btn').addEventListener('click', () => {
        document.body.removeChild(modal);
    });
}